import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

// src/utils/request.ts
const service = axios.create({
    baseURL: 'http://localhost:8080', // 直接连接后端
    timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(config => {
    // const authStore = useAuthStore()
    // 从localStorage直接获取，避免Pinia未初始化
     const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
    return config
})

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 对blob类型响应保持完整结构
        if (response.config.responseType === 'blob') {
            return response
        }
        return response.data
    },
    error => {
        if (error.response?.status === 401) {
            const authStore = useAuthStore()
            authStore.logout()
            router.push('/login')
        }
        return Promise.reject(error)
    }
)

export default service
